//Documentation complete
/**
 * @author Alex
 * @version 2009FE02
 */

package utilities;

import problemDomain.*;

import java.util.Iterator;
import java.util.List;

/**
 * Methods to encapsulate various problem domain objects in XML.
 */
public class XMLTools {
	
	/* Constants */
	
	private static final String XML_HEADER = "<?xml version=\"1.0\" ?>";
	
	/* END Constants */
	
	
	/* Static Methods */
	
	/**
	 * Encapsulates a <code>List</code> of <code>Bean</code> objects into an XML document for AJAX transmission.
	 * @param list the <code>List</code> of <code>Bean</code>
	 * @param rootTag a <code>String</code> containing the root tag name for the XML fragment
	 * @return the XML <code>String</code>
	 */
	public static String encapsulateBeanListXML (List<? extends Bean> list, String rootTag) {
		StringBuilder sb = new StringBuilder();
		sb.append('<' + rootTag + '>');
		if (list != null && list.size() != 0) {
			Iterator<? extends Bean> i = list.iterator();
			while (i.hasNext())
				sb.append(i.next().toXML());
		}
		sb.append("</" + rootTag + '>');
		return sb.toString();
	}
	
	/**
	 * Encapsulates a <code>List</code> of <code>String</code> into an XML document for AJAX transmission. 
	 * @param list the <code>List</code> of <code>String</code>
	 * @return the XML <code>String</code>
	 */
	public static String encapsulateStringListXML (List<String> list) {
		StringBuffer sb = new StringBuffer();
		sb.append(XML_HEADER);
		sb.append("<types>");
		Iterator<String> i = list.iterator();
		while (i.hasNext()) {
			String str = i.next();
			sb.append("<type>");
			sb.append("<name>" + str + "</name>");
			sb.append("</type>");
		}
		sb.append("</types>");
		return sb.toString();
	}
	
	/**
	 * Encodes HTML forbidden characters as entities (ex. &amp;)
	 * @param s the <code>String</code> to encode
	 * @return the encoded <code>String</code>
	 */
	public static String encodeEntities (String s) {
		StringBuilder buf = new StringBuilder(s.length());
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '<' || c == '>' || c == '/' || c == '-')
				buf.append(c);
			else
				buf.append("&#").append((int)c).append(";");
		}
		return buf.toString();
	}
	
	
	/* END Static Methods */
	
}
